<?php
defined('IN_PHPCMS') or exit('No permission resources.');
//模型缓存路径
define('CACHE_MODEL_PATH',CACHE_PATH.'caches_model'.DIRECTORY_SEPARATOR.'caches_data'.DIRECTORY_SEPARATOR);
pc_base::load_app_func('global');
pc_base::load_sys_class('form', '', 0);
class order{
	private $db;
	function __construct() {
		$this->db = pc_base::load_model('cart_model');
		$this->db2 = pc_base::load_model('product_model');
		$this->db3 = pc_base::load_model('session_model');
		$this->_userid = param::get_cookie('_userid');
		$this->_username = param::get_cookie('_username');
		$this->_groupid = param::get_cookie('_groupid');
		$this->address = pc_base::load_model('consignee_address_model');
		$this->bonus = pc_base::load_model('ushop_bonus_model');
		$this->bonus_type = pc_base::load_model('ushop_bonus_type_model');
		$this->order = pc_base::load_model('order_info_model');
	}
	public function init(){
		if(isset($_GET['siteid'])) {$siteid = intval($_GET['siteid']);} else {$siteid = 1;}
		$sitelist  = getcache('sitelist','commons');
		$default_style = $sitelist[$siteid]['default_style'];
		$CATEGORYS = getcache('category_content_'.$siteid,'ushop');
		$ip = ip();
		$SESSION = $this->db3->get_one(array('ip'=>$ip), 'sessionid');
		if($SESSION || $_COOKIE['PHPSESSID']){
			$result = $this->db->select(array('sessionid'=>$SESSION['sessionid'],'is_real'=>'0'));
		}else{
			$cart['ushopsessid']	= $_COOKIE['ushop_cart'];
			$result = $this->db->select(array('ushopsessid'=>$_COOKIE['ushop_cart'],'is_real'=>'0'));
		}
		switch($_GET['step']){
			case 'init':
				foreach($result as $k=>$v){
				$data[$k]= ' <tr class="align_Center" id=Goods_amount_'.$v['rec_id'].'>
				  <td style="padding:5px 0 5px 0;">'.$v['goodsid'].'</td>
				  <input name="recid" type="hidden" value="'.$v['rec_id'].'">
				  <td class="align_Left"><div class="p-img"><a target="_blank" href=""><img src="'.$v['thumb'].'"></a></div>
					<span><a target="_blank" href="'.$v['gurl'].'">'.$v['title'].'</a></span>
					<div>
					<span class="tip_bag">[赠品]</span>赠品笔记本电脑内存<font color="red">×1</font><span>
					<input name="delGiftBtn" type="hidden" value=""></span></div></td>
				  <td><span class="price">￥'.$v['price'].'</span></td>
				  <td><span class="price">100分</span></td>
				  <td>￥0.00</td>
				  <td>0</td>
				  <td>
				  <a onclick="setAmount.reduce(\'#amount_'.$v['rec_id'].'\')" href="javascript:void(0)" title="减一" style="margin-right:2px;"><img style="display:inline" src="'.IMG_PATH.'ushop/bag_close.gif" border="none"></a>
			   <input rel="tag-flowers-closeup" type="text" id="amount_'.$v['rec_id'].'" maxlength="4" style="width:30px" value="'.$v['number'].'" onblur="changeProductCount(\''.$v['rec_id'].'\',this);" onfocus="changeTxtOnFocus(\''.$v['rec_id'].'\',this);"  onkeyup="setAmount.modify(\'#amount_'.$v['rec_id'].'\')" >
					<a onclick="setAmount.add(\'#amount_'.$v['rec_id'].'\')" href="javascript:void(0)" title="加一"  style="margin-left:2px;"><img style="display:inline" src="'.IMG_PATH.'ushop/bag_open.gif" border="none"></a>
					</td>
				  <td><a href="" onclick="RemoveProduct('.$v['rec_id'].','.$v['number'].')" id="btn_del_515312" >删除</a></td>
				</tr>
			  ';	
			$price +=$v['price']*$v['number'];				
		}
			$data['count']= '<tr class="count_foot">
			  <td class="align_Right Tfoot" colspan="9" style="height:30px">重量总计：2.52kg&nbsp;&nbsp;&nbsp;原始金额：￥'.$price.'元 - 返现：￥0.00元<br>
				<span style="font-size:14px"><b>商品总金额：<span class="price" id="cartBottom_price">￥'.$price.'</span>元</b></span></td>
			</tr>
				';
			$nickname = trim(get_nickname(),'(,)');
			$nickname = empty($nickname) ? 0: 1;
			$style = 'initcart';
			break;
			case 'check':
				setcookie('onlypost','y');
				//收获人信息
				$infos = $this->address->get_one(array('user_id'=>$this->_userid,'is_default'=>1),'*','address_id DESC');
				//商品清单
				$ip = ip();
				$SESSION = $this->db3->get_one(array('ip'=>$ip), 'sessionid');
				if($SESSION || $_COOKIE['PHPSESSID']){
					$result = $this->db->select(array('sessionid'=>$SESSION['sessionid'],'is_real'=>'0'));
				}else{
					$cart['ushopsessid']	= $_COOKIE['ushop_cart'];
					$result = $this->db->select(array('ushopsessid'=>$_COOKIE['ushop_cart'],'is_real'=>'0'));
				}
				foreach($result as $key => $value) {
					//商品总金额
					$price +=$value['price']*$value['number'];
					//获取会员级信息
					$groupid = get_memberinfo($this->_userid,'groupid');
					//获取会员级的价格
					$catid = $value['catid'];
					$siteid = isset($_GET['siteid']) ? intval($_GET['siteid']) : get_siteid();
					$CATEGORYS = getcache('category_content_'.$siteid,'ushop');	
					if(!isset($CATEGORYS[$catid]) || $CATEGORYS[$catid]['type']!=0) exit(L('information_does_not_exist'));
					$MODEL = getcache('ushop_model','model');
					$tablename = $this->db2->table_name = $this->db->db_tablepre.$MODEL[$CATEGORYS[$catid]['modelid']]['tablename'];
					
					$goodsinfo = $this->db2->get_one(array('id'=>$value['goodsid']));
					$member_price = $goodsinfo['member'];
					$memberprice = unserialize($member_price);
					if($memberprice[$groupid] == 0) {$memberprice[$groupid] = 1;}
					$memberPrice += (1-number_format($memberprice[$groupid],5))*$value['price']*$value['number'];
					//折上折
					$discount = $goodsinfo['discount'];
					$discountpricekey = unserialize($discount);
					$discountpricekey_array = array_combine($discountpricekey[1],$discountpricekey[2]);
					krsort($discountpricekey_array);
					foreach($discountpricekey_array as $keys => $data) {
						if($value['number'] >= $keys) {
							$discountPrice += (1-number_format($discountpricekey_array[$keys],5))*($value['price']*$value['number'] - (1-number_format($memberprice[$groupid],5))*$value['price']*$value['number']);
							
							$result[$key]['actual_price'] = $value['price'] - (1-number_format($memberprice[$groupid],5))*$value['price']*$value['number'] -(1-number_format($discountpricekey_array[$keys],5))*($value['price']*$value['number'] - (1-number_format($memberprice[$groupid],5))*$value['price']*$value['number']);
							
							break;
						}
					}
					//商品红包
					$bonusid = isset($goodsinfo['bonus_type_id']) && !empty($goodsinfo['bonus_type_id']) ? $goodsinfo['bonus_type_id'] : '';
					if(!empty($bonusid)) {
						$bonusarray = explode(":",$bonusid);
					}
					foreach($bonusarray as $bonus_id) {
						$bonusinfo = $this->bonus_type->get_one(array('type_id'=>$bonus_id));
						
						if(!empty($bonusinfo)) {
							if((SYS_TIME > $bonusinfo['use_start_date']) &&(SYS_TIME < $bonusinfo['use_end_date']) && ($value['price']*$value['number'] >= $bonusinfo['min_goods_amount']) ) {
								$bonus_money += $bonusinfo['type_money'];
							}
						}
					}
				}	
							
				//用户红包
				$member_bonusid = $this->bonus->listinfo(array('user_id'=>$this->_userid,'is_user' => 0));
				foreach($member_bonusid as $member_bonus_id) {
					$member_bonusinfo = $this->bonus_type->get_one(array('type_id'=>$member_bonus_id['bonus_type_id']));
					if(!empty($member_bonusinfo)) {
						if((SYS_TIME > $member_bonusinfo['use_start_date']) &&(SYS_TIME < $member_bonusinfo['use_end_date']) && ($price >= $member_bonusinfo['min_goods_amount']) ) {
							$member_bonus_money += $member_bonusinfo['type_money'];
						}
					}
				}
				//按订单金额红包
				$where = 'send_type=2 and use_start_date <='.SYS_TIME.' and use_end_date >='.SYS_TIME;
				$orderAmountBonus = $this->bonus_type->listinfo($where);
				uasort($orderAmountBonus,'order_by_bonus');
				foreach($orderAmountBonus as $k => $order_amount_bonus) {
					if($price >= $order_amount_bonus['min_amount']) {
						$order_amount_bonus_money = $order_amount_bonus['type_money'];
						break;
					}
				}
				if(empty($bonus_money)) {$bonus_money = '0.00';}
				if(empty($member_bonus_money)) {$member_bonus_money = '0.00';}
				if(empty($order_amount_bonus_money)) {$order_amount_bonus_money = '0.00';}
				$theTotalAmount = number_format($price - $memberPrice - $discountPrice - $bonus_money - $member_bonus_money - $order_amount_bonus_money,2,'.','');
				$result_array = serialize($result);
			$style = 'checkcart';
			break;
			case 'success':
				if(isset($_POST['dosubmit']) && !empty($_POST['dosubmit']) && $_COOKIE['onlypost'] == 'y') {
					//订单号
					$order_sn = date('y').date('m').date('d').random(4);
					$pay_style = $_POST['IdPaymentType'];
					$delivery = $_POST['IdShipmentType'];
					$theTotalAmount = $_POST['theTotalAmount'];
					$this->bonus->update(array('bonus_sn'=>$order_sn),array('user_id'=>$this->_userid));
					$_POST[info]['order_sn'] = $order_sn;
					$_POST[info]['address_id'] = $_POST['address_id'];
					$_POST[info]['user_id'] = $this->_userid;
					$_POST[info]['integral'] = count(explode(":",trim($_POST['goods_id'],":")))*100;
					$_POST[info]['pay_style'] = $pay_style;
					$_POST[info]['shipping_time'] = SYS_TIME;
					$consignee = $this->address->get_one(array('user_id'=>$this->_userid,'is_default'=>1));
					$_POST[info]['consignee'] = $consignee['consignee'];
					$_POST[info]['goods_id'] = new_stripslashes($_POST['goods_info']);
					$this->order->insert($_POST[info],true);
					$this->bonus->update(array('is_user'=>1,'used_time'=>SYS_TIME),array('user_id'=>$this->_userid));
				}
				setcookie('onlypost','n');
			$style = 'endcart';
			break;
			default:
				$style = 'initcart';
		}
		
		include template('ushop',$style,$default_style);
	}
	/**
		订单列表
		添加到购物车
	*/	
	public function public_add_cart(){
		$catid = intval($_POST['catid']);
		$id = intval($_POST['id']);
		$amount = intval($_POST['number']);
		$siteids = getcache('category_content','ushop');
		$siteid = $siteids[$catid];
		$CATEGORYS = getcache('category_content_'.$siteid,'ushop');	
		if(!isset($CATEGORYS[$catid]) || $CATEGORYS[$catid]['type']!=0) exit(L('information_does_not_exist'));
		$this->category = $CAT = $CATEGORYS[$catid];
		$this->category_setting = $CAT['setting'] = string2array($this->category['setting']);
		$siteid = $GLOBALS['siteid'] = $CAT['siteid'];
		$MODEL = getcache('ushop_model','model');
		$modelid = $CAT['modelid'];
		$tablename = $this->db2->table_name = $this->db->db_tablepre.$MODEL[$modelid]['tablename'];
		$r = $this->db2->get_one(array('id'=>$id));
		if(!$r || $r['status'] != 99) exit(L('info_does_not_exists'));
		$this->db2->table_name = $tablename.'_data';
		$r2 = $this->db2->get_one(array('id'=>$id));
		$rs = $r2 ? array_merge($r,$r2) : $r;
		$cart['userid']  = $this->_userid?$this->_userid:'0';
		$ip = ip();
		$SESSION = $this->db3->get_one(array('ip'=>$ip), 'sessionid');
		if($SESSION){
			$cart['sessionid']  = $SESSION['sessionid'];
			$this->db->update(array('sessionid'=>$cart['sessionid'],'userid'=>$cart['userid']),array('ushopsessid'=>$_COOKIE['ushop_cart']));
		}else{
			$cart['sessionid']  = isset($SESSION['sessionid'])?isset($SESSION['sessionid']):$_COOKIE['PHPSESSID'];
			$cart['ushopsessid']	= $_COOKIE['ushop_cart'];
			$cart['type']	= '1';
		}
		$cart['pno']  = $rs['pno'];
		$cart['thumb']  = $rs['thumb'];
		$cart['gurl']  = $rs['url'];
		$cart['goodsid']  = $rs['id'];
		$cart['catid']  = $rs['catid'];
		$cart['title']  = $rs['title'];
		$cart['market']  = $rs['market'];
		$cart['price']  = $rs['price'];
		$cart['number']  = $amount;
		$cart['is_real']  = $rs['is_real'];
		$cart['point'] = $rs['point'];
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest"){
			 $this->db->insert($cart);
		}else{return false;}	
	}		
	public function public_edit_cart(){
		$id=intval($_POST['id']);
		$number=intval($_POST['number']);
		if($id < '1')return false;
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest"){
			$ip = ip();
			$SESSION = $this->db3->get_one(array('ip'=>$ip), 'sessionid');
			if($SESSION || $_COOKIE['PHPSESSID']){
				$result = $this->db->update(array('number'=>$number),array('sessionid'=>$_COOKIE['PHPSESSID'],'rec_id'=>$id));
				exit($result);
			}else{
				$cart['ushopsessid']	= $_COOKIE['ushop_cart'];
				$result = $this->db->update(array('number'=>$number),array('ushopsessid'=>$_COOKIE['ushop_cart'],'rec_id'=>$id));
				exit($result);
			}
		}else{return false;}	
	}	
	
	public function public_get_josn_initcart(){
		$id=intval($_GET['id']);
		$data = $this->db->get_one(array('rec_id'=>$id));
		$datas['money'] = $data['price']*$data['number'];
		$datas['info']= ' <tr class="align_Center" id=Goods_amount_'.$data['rec_id'].'>
                          <td style="padding:5px 0 5px 0;">'.$data['goodsid'].'</td>
			  			  <input name="recid" type="hidden" value="'.$data['rec_id'].'">
             			  <td class="align_Left"><div class="p-img"><a target="_blank" href=""><img src="'.$data['thumb'].'"></a></div>
                          <span><a target="_blank" href="'.$data['gurl'].'">'.$data['title'].'</a></span>
                          <div><span class="tip_bag">[赠品]</span>赠品笔记本电脑内存<font color="red">×1</font><span>
						  <input name="delGiftBtn" type="hidden" value=""></span></div></td>
						  <td><span class="price">￥'.$data['price'].'</span></td>
						  <td><span class="price">100分</span></td><td>￥0.00</td><td>0</td><td>
						  <a onclick="setAmount.reduce(\'#amount_'.$data['rec_id'].'\')" href="javascript:void(0)" title="减一" style="margin-right:2px;"><img style="display:inline" src="'.IMG_PATH.'ushop/bag_close.gif" border="none"></a>
					      <input rel="tag-flowers-closeup" type="text" id="amount_'.$data['rec_id'].'" maxlength="4" style="width:30px" value="'.$data['number'].'" onblur="changeProductCount(\''.$data['rec_id'].'\',this);" onfocus="changeTxtOnFocus(\''.$data['rec_id'].'\',this);"  onkeyup="setAmount.modify(\'#amount_'.$data['rec_id'].'\')" >
						  <a onclick="setAmount.add(\'#amount_'.$data['rec_id'].'\')" href="javascript:void(0)" title="加一"  style="margin-left:2px;"><img style="display:inline" src="'.IMG_PATH.'ushop/bag_open.gif" border="none"></a>
						  </td><td><a href="" id="btn_del_515312" >删除</a></td></tr>';
						
						$ip = ip();
						$SESSION = $this->db3->get_one(array('ip'=>$ip), 'sessionid');
						if($SESSION || $_COOKIE['PHPSESSID']){
							$data2 = $this->db->listinfo(array('sessionid'=>$_COOKIE['PHPSESSID']));
							}else{
							$data2 = $this->db->listinfo(array('ushopsessid'=>$_COOKIE['ushop_cart']));
								}
						$price='';		
						foreach($data2 as $vs){		
							$price +=$vs['price']*$vs['number'];
							}	
					    $datas['count']= '<tr class="count_foot"><td class="align_Right Tfoot" colspan="9" style="height:30px">重量总计：2.52kg&nbsp;&nbsp;&nbsp;原始金额：￥ '.$price.'元 - 返现：￥0.00元<br>
								<span style="font-size:14px"><b>商品总金额：<span class="price" id="cartBottom_price">￥'.$price.'</span>元</b></span></td>
							</tr>
							';	
				echo json_encode($datas);
		}
	public function public_delte_cart(){
		$id=intval($_POST['id']);
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest"){
			$this->db->delete(array('rec_id'=>$id));
		}else{return false;}
		}	
		
		
	public function public_check_mycart(){
		header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header('Pragma: no-cache');
		$ip = ip();
		$SESSION = $this->db3->get_one(array('ip'=>$ip), 'sessionid');
		if($SESSION || $_COOKIE['PHPSESSID']){
				$result = $this->db->listinfo(array('sessionid'=>$SESSION['sessionid'],'is_real'=>'0'));
			}else{
				$cart['ushopsessid']= $_COOKIE['ushop_cart'];
				$result = $this->db->listinfo(array('ushopsessid'=>$_COOKIE['ushop_cart'],'is_real'=>'0'));
			}
		foreach($result as $v){
			$nums +=$v['number'];
			$money +=($v['number']*$v['price']);
		}
		$data =array('number'=>"$nums",'money'=>"$money",'items'=>$result);
		echo json_encode($data);	
	}	
	
	public function public_order_edit() {
		$style = $_GET['style'];
		switch ($style) {
			case 'member' :
				$address_id = intval($_REQUEST['id']);
				if($address < 0) return false;
				$this->address->update(array('is_default'=>0),array('user_id'=>$this->_userid));
				$info['user_id'] = $this->_userid;
				$info['consignee'] = $_REQUEST['consignee'];
				$info['consignee_address'] = $_REQUEST['province'].'&nbsp;&nbsp;&nbsp;'.$_REQUEST['city'].'&nbsp;&nbsp;&nbsp;'.$_REQUEST['area'];
				$info['consignee_more_address'] = $_REQUEST['consignee_more_address'];
				$info['consignee_zip'] = $_REQUEST['consignee_zip'];
				$info['consignee_pho'] = $_REQUEST['consignee_pho'];
				$info['consignee_email'] = $_REQUEST['consignee_email'];
				$info['is_default'] = 1;
				$this->address->insert($info,true);
				$infos = $this->address->get_one(array('user_id'=>$this->_userid,'is_default'=>1),'*','address_id DESC');
				exit(trim_script($_GET['callback']).'('.json_encode($infos).')');
			break;
		}
	}
	
	public function public_add_get(){
		exit(1);
	}
}
?>